<template>
  <div class="page">
    <t-nav-bar
        title="服务评价"
        left-text="返回"
        left-arrow
        @click-left="handleBack"
    />
    <div class="content">
      <!--    导航栏-->
      <t-navbar title="服务评价" :fixed="false" left-arrow>
        <template #right>
          <t-icon name="ellipsis" size="24px" />
        </template>
      </t-navbar>


      <!--      选项卡-->
      <t-tabs v-model="currentTab">
        <t-tab-panel value="first">
          <template #label>
            <div>待评价</div>
          </template>
        </t-tab-panel>
        <t-tab-panel value="second">
          <template #label>
            <div>已评价</div>
          </template>
        </t-tab-panel>
      </t-tabs>


      <!--      分割线-->
      <t-divider class="divider"/>


      <!--      维修记录卡片（待评价）-->
      <el-card v-if="currentTab === 'first' && maintenanceRecordsList.length > 0"
               v-for="record in maintenanceRecordsList"
               :key="record.maintenanceRecordId"
               style="max-width: 480px ;margin: 4px 0">
        <template #header>
          <div class="card-header">
            <span>维修记录ID:{{ record.maintenanceRecordsId }}</span>
            <span class="card-header-status" >已完成</span>
          </div>
        </template>
        <p class="text-base">标题：{{ record.title }}</p>
        <p class="text-base">维修类型：{{ record.type }}</p>
        <p class="text-base">报修地址：{{ record.repairAddress }}</p>
        <p class="text-base">报修时间：{{ record.repairTime }}</p>
        <div class="el-card_footer" >
          <div class="footer-buttons" >
            <el-button @click="openDrawer1(record)" type="primary" plain>查看详情</el-button>
            <el-button @click="openDrawer2(record)" type="primary">评价</el-button>
          </div>
        </div>
      </el-card>


      <!--      维修记录卡片（已评价）-->
      <el-card v-else
               v-for="record in maintenanceRecordsList"
               :key="record.maintenanceRecordId"
               style="max-width: 480px ;margin: 4px 0"
      >
        <template #header>
          <div class="card-header">
            <span>维修记录ID:{{ record.maintenanceRecordsId }}</span>
            <span class="card-header-status" >已完成</span>
          </div>
        </template>
        <p class="text-base">标题：{{ record.title }}</p>
        <p class="text-base">维修类型：{{ record.type }}</p>
        <p class="text-base">报修地址：{{ record.repairAddress }}</p>
        <p class="text-base">报修时间：{{ record.repairTime }}</p>
        <div class="el-card_footer"  >
          <div class="footer-buttons">
            <el-button @click="openDrawer1(record)" type="primary" plain>查看详情</el-button>
            <el-button @click="openDrawer3(record)" type="primary">查看评价</el-button>
          </div>
        </div>
      </el-card>


      <!--      点击查看详情按钮后-->
      <!--      维修记录详情抽屉-->
      <el-drawer v-model="drawer1" :direction="direction"  size="50%">
        <template #header>
          <h4>维修记录详情</h4>
        </template>
        <template #default>
          <p class="text-base">维修记录ID：{{detailMaintenanceRecords?.maintenanceRecordsId}}</p>
          <p class="text-base">标题：{{detailMaintenanceRecords?.title}}</p>
          <p class="text-base">维修类型：{{ detailMaintenanceRecords?.type }}</p>
          <p class="text-base">维修地址：{{ detailMaintenanceRecords?.repairAddress }}</p>
          <p class="text-base">故障描述：{{ detailMaintenanceRecords?.faultDescription }}</p>
          <p class="text-base">报修时间：{{ new Date(detailMaintenanceRecords?.repairTime).toLocaleString() }}</p>
          <p class="text-base">派工时间：{{ detailMaintenanceRecords?.dispatchTime }}</p>
          <p class="text-base">员工工号：{{ detailMaintenanceRecords?.employeeId }}</p>
          <p class="text-base">员工姓名：{{ detailMaintenanceRecords?.employeeName }}</p>
          <p class="text-base">维修详情：{{ detailMaintenanceRecords?.repairDetails }}</p>
          <p class="text-base">维修状态：{{ detailMaintenanceRecords?.maintenanceStatus }}</p>
        </template>
      </el-drawer>


      <!--      点击评价按钮后-->
      <!--      评价抽屉-->
      <el-drawer v-model="drawer2" :direction="direction" class="rate-drawer" size="40%">
        <template #header >
          <h4 >请填写评价</h4>
        </template>
        <template #default>
          <!--          综合评价区域-->
          <div class="rate-stars">
            <p >综合评价</p>
            <el-rate v-model="rating" size="large"/>
          </div>
          <t-divider class="divider"/>
          <!--          评价文本框区域-->
          <div>
            <el-input type="textarea" :rows="5" placeholder="请输入评价内容" v-model="textarea" />
          </div>
          <!--          提交按钮-->
          <div class="footer-buttons" >
            <el-button class="commit-button" :plain="true" @click="commitSuccess()" type="primary">提交评价</el-button>
          </div>
        </template>
      </el-drawer>


      <!--      点击查看评价按钮后-->
      <!--      查看评价抽屉-->
      <el-drawer v-model="drawer3" :direction="direction" class="rate-drawer" size="40%">
        <template #header >
          <h4 >查看你的评价</h4>
        </template>
        <template #default>
          <!--          综合评价区域-->
          <div class="rate-stars">
            <p >综合评价</p>
            <el-rate v-model="myRating" disabled size="large"/>
            <p style="font-size:13px;margin-left: 10px">{{ evaTime }}</p>
          </div>
          <t-divider class="divider"/>
          <!--          评价文本框区域-->
          <div>
            <p class="text-base">{{ myComments }}</p>
          </div>
        </template>
      </el-drawer>

    </div>
  </div>


</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import {createApp, ref, onMounted, watch} from 'vue';
import TDesign from 'tdesign-mobile-vue';
import ElementPlus from 'element-plus'
import {ElMessageBox}  from 'element-plus'
import type {DrawerProps }  from 'element-plus'
import { ElMessage } from 'element-plus'
import axios  from "axios";
import { useStore } from 'vuex';
import { Icon as TIcon } from 'tdesign-icons-vue-next';

// 引入组件库的少量全局样式变量
import 'tdesign-mobile-vue/es/style/index.css';
import 'element-plus/dist/index.css'
import App from "@/App.vue";

const app = createApp(App);
app.use(TDesign);

app.use(ElementPlus)
// app.mount('#app')

const userNo = ref('');
const store = useStore();
const currentTab = ref('first');//默认显示第一个选项卡(待评价)
//-----------维修记录卡片------------



// 页面加载时获取评价数据
onMounted(async () => {
  await fetchEveluations();
});
// 监听选项卡变化，重新获取评价数据
watch(currentTab, async (newValue) => {
  await fetchEveluations();
})

//----------待评价和已评价卡片------------

// 获取简洁版维修记录列表
// 定义维修记录列表的响应式变量
const maintenanceRecordsList = ref([]);
const fetchEveluations = async () => {
  try {
    const user = store.getters.user;
    console.log("获取登录用户信息", user);
    userNo.value = user.userNo;
    console.log("获取登录用户id", userNo.value);

    if (currentTab.value === 'first') {
      const response = await axios.post(`http://localhost:8003/maintenance-records/select_1/${userNo.value}/待评价`)
      maintenanceRecordsList.value = response.data;
    } else {
      const response = await axios.post(`http://localhost:8003/maintenance-records/select_1/${userNo.value}/已评价`)
      maintenanceRecordsList.value = response.data;
    }
  } catch (error){
    console.log("获取维修记录列表失败",error)
  }
}

//----------已评价卡片------------
/*const maintenanceRecordsList_2 = ref([]);
const showRecord = () => {
  axios.post(`http://localhost:8080/service-evaluation/getMaintenanceRecordsSimpleByUserNo_2/${userNo.value}`)
      .then(response => {
        // 假设后端返回的数据格式是{ data: List<MaintenanceShortRecordsdto> }
        maintenanceRecordsList_2.value = response.data;
        console.log("获取已评价维修记录列表成功----",response.data)
        console.log("获取已评价维修记录列表成功",maintenanceRecordsList_2.value)
      })
      .catch(error => {
        console.log("获取已评价维修记录列表失败",error)
      })
}*/

//---------维修记录详情抽屉----------
//点击查看详情按钮打开抽屉
const drawer1 = ref(false)
const direction = ref<DrawerProps['direction']>('btt') // 设置默认方向为从下到上
// 定义一个响应式变量来存储从后端获取的维修记录详情
const detailMaintenanceRecords= ref(null)
// 接收一个record参数
function openDrawer1(record) {
  // 打开抽屉
  drawer1.value = true
  console.log("查看详情",record)
  // 设置详细维修记录
  detailMaintenanceRecords.value = record.value;
  console.log("获取详细维修记录成功----",record.value)
  console.log("获取详细维修记录成功",detailMaintenanceRecords.value)
}


//---------评价抽屉----------
//点击评价按钮打开抽屉
const drawer2 = ref(false)
// 临时存储要评价的维修记录ID
const maintenanceRecordsID = ref('')
function openDrawer2(record) {
  drawer2.value = true
  maintenanceRecordsID.value = record.maintenanceRecordsId
  console.log("当前评价的维修记录ID",maintenanceRecordsID.value)
}
//评价星星区域
const rating = ref(0)
//评价文本框区域
const textarea = ref('')
//提交评价按钮
const commitSuccess = async () => {

  try {
    console.log("当前评价的维修记录ID---", maintenanceRecordsID.value)
    console.log(rating.value, textarea.value, userNo.value)

    const response = await axios.post(`http://localhost:8004/service-evaluation/addEvaluation`, {
      maintenanceRecordsId: maintenanceRecordsID.value,
      rating: rating.value,
      comments: textarea.value,
      userNo: userNo.value
    })
    console.log("评价成功----", response.data)
    if (response.data === "评价成功") {
      ElMessage({
        message: '提交成功',
        type: 'success',
      });
    } else {
      // 处理未知响应
      console.error("未知的服务器响应:", response.data);
      ElMessage({
        message: '服务器返回未知结果，请稍后再试。',
        type: 'warning',
      });
    }
  }catch (error) {
    // 错误处理
    console.error("提交评价时发生错误:", error);
    ElMessage({
      message: '提交失败，请检查网络连接或稍后再试。',
      type: 'error',
    });
  }
};


//---------查看评价抽屉----------
//点击查看评价按钮打开抽屉
// 存储从后端传进来的评价信息（评分，评轮，评价时间）
const myRating = ref('')
const myComments = ref('')
const evaTime = ref('')

const drawer3 = ref(false)
const openDrawer3 = async (record2) => {
  try {
    drawer3.value = true
    console.log("当前查看评价的维修记录ID", record2.maintenanceRecordsId.value)

    const response = await axios.post(`http://localhost:8004/service-evaluation/selectEvaluation/${record2.maintenanceRecordsId}`)
    // 后端传回的数据为response.data
    myRating.value = response.data.rating;
    myComments.value = response.data.comments;
    evaTime.value = response.data.evaTime;
    console.log("获取评价信息成功----", response.data)
  } catch (error) {
    console.error("获取评价信息失败:", error);
  }

};


const router = useRouter()
const handleBack = () => {
  router.push('http://localhost:5173/home')
}
</script>

<style scoped>
.page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  font-family: Arial, sans-serif;
  background-color: #f5f5f5;
}

.content {
  flex: 1;
  padding: 20px;
}


/*-----维修记录卡片-----*/
/*已完成字段*/
.card-header-status {
  float: right;
  color: #b2b2b2;
  font-size: 12px;
}


/*--------查看详情按钮---------*/
/*---------维修记录抽屉样式----------*/


/*------评价按钮-------*/
/*使评价按钮靠右边展示*/
.footer-buttons {
  display: flex;
  justify-content: flex-end;
}
/*评价按钮点击时的样式*/
.el-card_footer .footer-buttons .el-button:active {
  /* 点击时的样式 */
  background-color: #3a8ee6; /* 按钮背景色更深 */
  transform: scale(0.95); /* 按钮稍微缩小(不起作用) */
}


/*---------评价抽屉样式----------*/
/*抽屉总体样式*/
.rate-drawer {
  background-color: #f5f5f5;
}
/*评价星星区块*/
.rate-stars {
  display: flex;
  align-items: center;
}
.rate-stars p {
  margin-right: 20px;
  font-weight: bolder;
}
.commit-button {
  margin-top: 15px;
}


/*-----------查看评价抽屉样式----------*/
/*抽屉总体样式*/

.rate-drawer {
  background-color: #f5f5f5;
}
/*评价星星区块*/
.rate-stars {
  display: flex;
  align-items: center;
}
.rate-stars p {
  margin-right: 20px;
  font-weight: bolder;
}


/*-----------------------通用样式----------------------*/
/*分割线*/
.divider {
  margin: 10px 0;
}

/*居中标题*/
.center-text {
  text-align: center;
}

/*基本文本样式*/
.text-base {
  font-size: 14px;
}


</style>
